#!/usr/bin/env python3
#
# OpenBSD VM image
#
# Copyright 2017-2019 Red Hat Inc.
#
# Authors:
#  Fam Zheng <famz@redhat.com>
#  Gerd Hoffmann <kraxel@redhat.com>
#
# This code is licensed under the GPL version 2 or later.  See
# the COPYING file in the top-level directory.
#

import os
import sys
import socket
import subprocess
import basevm

class OpenBSDVM(basevm.BaseVM):
    name = "openbsd"
    arch = "x86_64"

    link = "https://cdn.openbsd.org/pub/OpenBSD/6.9/amd64/install69.iso"
    csum = "140d26548aec680e34bb5f82295414228e7f61e4f5e7951af066014fda2d6e43"
    size = "20G"
    pkgs = [
        # tools
        "git",
        "pkgconf",
        "bzip2", "xz",
        "ninja",

        # gnu tools
        "bash",
        "gmake",
        "gsed",
        "gettext-tools",

        # libs: usb
        "libusb1--",

        # libs: crypto
        "gnutls",

        # libs: images
        "jpeg",
        "png",

	# libs: ui
        "sdl2",
        "gtk+3",
        "libxkbcommon",

        # libs: migration
        "zstd",
    ]

    BUILD_SCRIPT = """
        set -e;
        rm -rf /home/qemu/qemu-test.*
        cd $(mktemp -d /home/qemu/qemu-test.XXXXXX);
        mkdir src build; cd src;
        tar -xf /dev/rsd1c;
        cd ../build
        ../src/configure --cc=cc --python=python3 {configure_opts};
        gmake --output-sync -j{jobs} {target} {verbose};
    """
    poweroff = "halt -p"

    def build_image(self, img):
        self.print_step("Downloading install iso")
        cimg = self._download_with_cache(self.link, sha256sum=self.csum)
        img_tmp = img + ".tmp"
        iso = img + ".install.iso"

        self.print_step("Preparing iso and disk image")
        subprocess.check_call(["cp", "-f", cimg, iso])
        self.exec_qemu_img("create", "-f", "qcow2", img_tmp, self.size)

        self.print_step("Booting installer")
        self.boot(img_tmp, extra_args = [
            "-bios", "pc-bios/bios-256k.bin",
            "-machine", "graphics=off",
            "-device", "VGA",
            "-cdrom", iso
        ])
        self.console_init()
        self.console_wait_send("boot>", "set tty com0\n")
        self.console_wait_send("boot>", "\n")

        # pre-install configuration
        self.console_wait_send("(I)nstall",               "i\n")
        self.console_wait_send("Terminal type",           "xterm\n")
        self.console_wait_send("System hostname",         "openbsd\n")
        self.console_wait_send("Which network interface", "vio0\n")
        self.console_wait_send("IPv4 address",            "dhcp\n")
        self.console_wait_send("IPv6 address",            "none\n")
        self.console_wait_send("Which network interface", "done\n")
        self.console_wait_send("DNS domain name",         "localnet\n")
        self.console_wait("Password for root account")
        self.console_send("%s\n" % self._config["root_pass"])
        self.console_wait("Password for root account")
        self.console_send("%s\n" % self._config["root_pass"])
        self.console_wait_send("Start sshd(8)",           "yes\n")
        self.console_wait_send("X Window System",         "\n")
        self.console_wait_send("xenodm",                  "\n")
        self.console_wait_send("console to com0",         "\n")
        self.console_wait_send("Which speed",             "\n")

        self.console_wait("Setup a user")
        self.console_send("%s\n" % self._config["guest_user"])
        self.console_wait("Full name")
        self.console_send("%s\n" % self._config["guest_user"])
        self.console_wait("Password")
        self.console_send("%s\n" % self._config["guest_pass"])
        self.console_wait("Password")
        self.console_send("%s\n" % self._config["guest_pass"])

        self.console_wait_send("Allow root ssh login",    "yes\n")
        self.console_wait_send("timezone",                "UTC\n")
        self.console_wait_send("root disk",               "\n")
        self.console_wait_send("(W)hole disk",            "\n")
        self.console_wait_send("(A)uto layout",           "\n")
        self.console_wait_send("Location of sets",        "cd0\n")
        self.console_wait_send("Pathname to the sets",    "\n")
        self.console_wait_send("Set name(s)",             "\n")
        self.console_wait_send("without verification",    "yes\n")

        self.print_step("Installation started now, this will take a while")
        self.console_wait_send("Location of sets",        "done\n")

        self.console_wait("successfully completed")
        self.print_step("Installation finished, rebooting")
        self.console_wait_send("(R)eboot",                "reboot\n")

        # setup qemu user
        prompt = "$"
        self.console_ssh_init(prompt, self._config["guest_user"],
                                      self._config["guest_pass"])
        self.console_wait_send(prompt, "exit\n")

        # setup root user
        prompt = "openbsd#"
        self.console_ssh_init(prompt, "root", self._config["root_pass"])
        self.console_sshd_config(prompt)

        # setup virtio-blk #1 (tarfile)
        self.console_wait(prompt)
        self.console_send("echo 'chmod 666 /dev/rsd1c' >> /etc/rc.local\n")

        # enable w+x for /home
        self.console_wait(prompt)
        self.console_send("sed -i -e '/home/s/rw,/rw,wxallowed,/' /etc/fstab\n")

        # tweak datasize limit
        self.console_wait(prompt)
        self.console_send("sed -i -e 's/\\(datasize[^=]*\\)=[^:]*/\\1=infinity/' /etc/login.conf\n")

        # use http (be proxy cache friendly)
        self.console_wait(prompt)
        self.console_send("sed -i -e 's/https/http/' /etc/installurl\n")

        self.print_step("Configuration finished, rebooting")
        self.console_wait_send(prompt, "reboot\n")
        self.console_wait("login:")
        self.wait_ssh()

        self.print_step("Installing packages")
        self.ssh_root_check("pkg_add %s\n" % " ".join(self.pkgs))

        # shutdown
        self.ssh_root(self.poweroff)
        self.wait()

        if os.path.exists(img):
            os.remove(img)
        os.rename(img_tmp, img)
        os.remove(iso)
        self.print_step("All done")

if __name__ == "__main__":
    sys.exit(basevm.main(OpenBSDVM))
